<?php

namespace spcj;
class Statistic
{
    public function run()
    {
        var_dump(date_default_timezone_get());
        $this->_created_int();

        //处理访问数
        $sql2 = "select * FROM (
select count(id) as view_num,DATE_FORMAT(us_at, '%Y%m%d') as d,shop_id from ddhd_sp_ip_logs  where lp_type=2 and is_deduplicated=1  group by shop_id,d
) as a order by d desc,shop_id asc limit 80";
        $collection  = DbConn::getConn()->query($sql2);
        foreach ($collection as $row){
            $this->spcj_row($row);
        }

        // 处理订单数
        $sql = "select * from (
select count(id) as order_num,sum(is_repurchase) as order_jg_num,sum(repurchase_price) as moneys_jg,sum(total_price) as moneys,shop_id,DATE_FORMAT(FROM_UNIXTIME(created_int-57600), '%Y%m%d') as d from ddhd_sp_orders where order_status=1 and created_int > 0  group by shop_id,d
) as a order by d desc,shop_id asc limit 80";
        $collection  = DbConn::getConn()->query($sql);
        if ($collection){
            foreach ($collection as $row){
                $this->spcj_row($row);
            }
        }
    }

    // 处理单行数据
    private function spcj_row($row){
        // 如果为空的去掉
        foreach ($row as $k => $v){
            if (!$row[$k]){
                unset($row[$k]);
            }
        }

        if (!isset($row['shop_id']) || !isset($row['d'])){
            return;
        }

        $id = DbConn::getConn()->table('ddhd_sp_statistics')->where('shop_id',$row['shop_id'])
            ->where('d',$row['d'])
            ->value('id');

        if ($id){
            DbConn::getConn()->table('ddhd_sp_statistics')->where('id',$id)->update($row);
        }else{
            DbConn::getConn()->table('ddhd_sp_statistics')->insert($row);
        }
    }

    /**
     * 创建时间戳
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _created_int()
    {
        $list = DbConn::getConn()->table('ddhd_sp_orders')
            ->where('created_int',0)
            ->where('created_date','<>','')
            ->field('id,created_int,created_date')
            ->select();
        if ($list){
            foreach ($list as $row){
                // 创建一个 DateTime 对象，并自动解析时区偏移
                $dateTime = new \DateTime($row['created_date']);

                // 获取 Unix 时间戳
                $created_int = $dateTime->getTimestamp();

                DbConn::getConn()->table('ddhd_sp_orders')->where('id', $row['id'])
                    ->update(['created_int' => $created_int]);
            }
        }
    }
}
